import { FunctionBlockModel, PageModel, PageType } from './pages/user/data';
import { addFunctionBlockInfo, addPageInfo } from './pages/user/PageInfo/api';
import routes from './router/routes';
import { RouteConfig } from './router/type';
// eslint-disable-next-line require-jsdoc
async function setPage(routes: RouteConfig[], parentId: string | null) {
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route.meta?.auth) {
      const isPage = !route.routes;
      // eslint-disable-next-line no-await-in-loop
      const { ok, data } = await addPageInfo({
        label: route.meta.title,
        permissionPid: parentId,
        actionUrl: route.path as string,
        router: route.name,
        sort: i,
        type: PageType.enum[isPage ? '页面' : '菜单']
      } as PageModel);
      if (ok) {
        const { id } = data;
        if (isPage) {
          const buttonList = route.meta?.buttonList ?? [];
          // eslint-disable-next-line no-restricted-syntax
          for (const btn of buttonList) {
            btn.pageId = id;
            // eslint-disable-next-line no-await-in-loop
            await addFunctionBlockInfo(btn as FunctionBlockModel);
          }
        } else {
          setPage(route.routes!, id);
        }
      }
    }
  }
}
window.setPage = () => setPage(routes, null);
